/**
 * Created by hjqi on 2016/4/19.
 */
//var libK8s = require('../lib/k8s/kubernetes');
//var _k8s = new libK8s();
var express = require('express');
var router = express.Router();
var _k8s_adp = require('../lib/k8s/k8sAdpter');
//var _k8s = _k8s_adp.getK8s();

var libcAdvisor = require('../lib/cadvisor/cadvisor');
var _libcAdvisor = new libcAdvisor();
var libInfluxdb = require('../lib/influxdb/influxdb');
var _libInfluxdb = new libInfluxdb();
var httpHandler = require('../lib/common/resultHandler') ;
var logger = require('../lib/log4js/log4js').logger('apiMonitor');

router.post('/getPodsList',function(req, res, next){
    var param =  req.body;
    var _username = req.username;

    var _svc = param;
    //_k8s = _k8s_adp.getK8s(_svc.clusterId);

    _k8s_adp.getK8s(_svc.clusterId).then(function(_k8s){
        return _k8s.getAppPodStatus(_username,param.app);
    }).then(function(pods){
        var _json = JSON.parse(pods);
        var podIdList = [];
        _json.items.forEach(function(pod){
            var _id = pod.metadata.name+'_'+pod.metadata.namespace+'_'+pod.metadata.uid;
            var _name = pod.metadata.name;
            podIdList.push({
                id:_id,
                name:_name
            });
        });
        res.send(podIdList);

    }).catch(function(e){
        resolveException("getPodsList", e,param ) ;
        res.status(400);
        res.send(e);
    });
});
/**
 * get status from cAdvisor
 */
router.post('/getStatus',function(req, res, next){
    var param =  req.body;
    var _username = req.username;

    _libcAdvisor.getStatus(param.id).then(function(status){
        res.send(JSON.parse(status).stats);
    }).catch(function(e){
        resolveException("getStatus", e,param ) ;
        res.status(400);
        res.send(e);
    });
});

/**
 * query the influx database
 */
router.post('/getInfluxdbQuery',function(req, res, next){
    var param =  req.body;
    var _username = req.username;//we set namespace =${username} when initializing
    var _queryparam ;

    //if collector is Heapster , database is k8s
    if( param.collector && param.collector==="heapster"){
        _queryparam = getk8QueryString( param ,_username ) ;
        _libInfluxdb.queryK8s(_queryparam,param.clsuterId ).then(function ( ret){
            if( !ret ){
                ret = {} ;
                ret.data = {} ;
            }
            var _retObj = JSON.parse(ret.data);
            if(!ret || _retObj.results[0].series === undefined)
                res.send([]);
            else{
               // console.log(_retObj.results[0].series[0].values[0]);
                res.send(_retObj.results[0].series[0].values);
            }
        }).catch(function(e){
            try{
                httpHandler.httpBadEnd(res,e,logger,"Exception occured when querying InfluxDb.k8s."+param.table ) ;
            }catch(ex){
                logger.error( JSON.stringify( ex )) ;
            }
        });
        return ;
    }

    var interval = (param.interval === 0?'':' and time >= now() - '+param.interval+'s');
    var limits =  (param.limits === undefined?'':' limit '+param.limits);
    var _q = 'select value  from '+param.table+' where container_name =~ /k8s_POD..*'+param.id +'.*/ and time <= now() '+interval+' order by time desc '+limits;

    var _ts = (new Date()).getTime();
    var _queryparam = {
        q:encodeURIComponent(_q),
        db:'cadvisor',
        _ts:_ts
    }

    _libInfluxdb.query(_queryparam).then( function ( ret){
        if( !ret ){
            ret = {} ;
            ret.data = {} ;
        }
        var _retObj = JSON.parse(ret.data);
        if(!ret || _retObj.results[0].series === undefined)
            res.send([]);
        else{
            console.log(_retObj.results[0].series[0].values[0]);
            res.send(_retObj.results[0].series[0].values);
        }
    }).catch(function(e){
        httpHandler.httpBadEnd(res,e,logger,"Exception occured when querying InfluxDb.cadvisor."+param.table ) ;
    });
});
/**
 * get query string from http request
 * param's format like below:
 * {
        table: 'tx_bytes',
        id: id,
        interval: interval,
        limits: limits,
        collector:"heapster"
    }
 */
function getk8QueryString(param,_username){
    //TODO
    var type = "pod" ;  //default level is pod
    var interval = (param.interval === 0?'':' and time >= now() - '+param.interval+'m ');//intervals before x minutes ago
    if( param.table === "cpu_usage_total" ) param.table = "cpu/usage" ;
    if( param.table === "memory_usage" ) param.table = "memory/usage" ;
    if ( param.table === "rx_bytes" ) param.table = "network/rx" ;
    if ( param.table === "tx_bytes" ) param.table = "network/tx" ;
    if( param.type ==="container"){
        type='pod_container' ;
    }

    var _q = " select value  from \""+param.table+"\""
        +" where pod_namespace ='"+_username+"'"
        +" and type='"+type+"'"
        +" and pod_name='"+param.id +"'"
        +" and time <= now() "+interval
        +  (param.limits === undefined?' limit 20':' limit '+param.limits); //default limitation is 20
    logger.debug("query:"+_q) ;
    var _ts = (new Date()).getTime();
    var _queryparam = {
        q:encodeURIComponent(_q),
        _ts:_ts
    }
    return _queryparam ;
}
/**
 * log the exception and param for  Reappearance of scene
 */
function resolveException(method,exception,data){
    if( !exception ) exception = {} ;
    if( !data ) data = {} ;
    if( logger != undefined )
        logger.error( "Exception ocurred when invoke #"+method+" with "+JSON.stringify( data )+","+JSON.stringify( exception ) ) ;
    else{
        console.log( "Exception ocurred when invoke #"+method+" with "+JSON.stringify( data )+","+JSON.stringify( exception ) ) ;
    }
}

module.exports = router;